Component Mounting Lifecycle Methods in ReactJS

mounting-lifecycle

Mounting is the process of creating an element and inserting it in a DOM tree.

Following methods are called in following order when an instance of a component is being created and inserted into the DOM:-

  • Constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount()

Constructor():-

The constructor for a React component is called before it is mounted. It is a special function that will get called whenever a new component is created. super(props) Directly overwrite this.state.

React constructor are only used for two purposes:

initializing state

Ex: this.state ={name:”Tutorials website”}

Binding the event handlers

Ex:- this.handleClick= this.handleClick.bind(this);

getDerivedStateFromProps(props,state):-

getDerivedStateFromProps is invoked right before calling the render method. When the state of the component depends on changes in props over time, Set the state. This method doesn’t have access to the component instance.

render():-

The render() method is the only required method in a class component.

  • Only the required method
  • Read props & state and return JSX
  • Children component lifecycle methods are also executed.

componentDidMount():-

componentDidMount() is invoked immediately after a component is mounted. This method is executed once in a lifecycle of a component and after the first render() method.

  • This is the best place to perform any ajax calls to load data.
  • The API calls should be made in the componentDidMount method always.

Let’s create an example to understand the mounting lifecycle method

Lifecycle Methods in ReactJS

Passing Arguments to Event Handlers

Related posts